package com.tinygray.lock;

import lombok.SneakyThrows;

public class DeadLockDemo {
    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";
        HoldLockResource holdLockResource = new HoldLockResource(lockA, lockB);
        HoldLockResource holdLockResource1 = new HoldLockResource(lockB, lockA);
        new Thread(holdLockResource,"lockA").start();
        new Thread(holdLockResource1,"lockB").start();
    }
}

class HoldLockResource implements Runnable {

    public HoldLockResource(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    private String lockA;
    private String lockB;

    @SneakyThrows
    @Override
    public void run() {
        synchronized (lockA){
            System.out.println(Thread.currentThread().getName() + "\t持有锁"+lockA + "尝试获得锁"+lockB);
            Thread.currentThread().join(2000);
            synchronized (lockB){
                System.out.println(Thread.currentThread().getName() + "\t持有锁" + lockB + "尝试获得锁" + lockA);
            }
        }
    }
}
